/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufba.lasid.ds.fd;

import br.ufba.lasid.comm.api.ICommunicator;
import br.ufba.lasid.comm.api.IHost;
import br.ufba.lasid.ds.fd.api.IFailureDetector;
import br.ufba.lasid.ds.fd.api.IFailureDetector.ModuleTypes;
import br.ufba.lasid.ds.fd.api.IFailureDetectorStateReporterModule;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author aliriosa
 */
public class FailureDetectorStateReporter implements IFailureDetectorStateReporterModule{
    
    IFailureDetector detector;
    private static final Log logger = LogFactory.getLog(FailureDetector.class);

    public FailureDetectorStateReporter(IFailureDetector detector) {
        this.detector = detector;
    }

    public FailureDetectorStateReporter() {
    }
        
    @Override
    public ModuleTypes getModuleType() throws Exception {
        return ModuleTypes.StateReporter;
    }

    @Override
    public void setFailureDetector(IFailureDetector detector) throws Exception {
        this.detector = detector;
    }

    @Override
    public synchronized void startup() throws Exception {
        new Thread(this).start();
    }

    @Override
    public synchronized void run() {
        try {
            IHost host = detector.getLocalhost();
            ICommunicator communicator = detector.getCommunicator();
            
            //logger.info(" host ==>" + host);
            host.updateState();
            
            String message = IFailureDetector.Utils.newMessage(
                                    IFailureDetector.MessageKinds.StateReport, 
                                    host.getResourcetable()
                              );
            
            communicator.send(host.getID(), detector.getName(), message);
            
        } catch (Exception ex) {
            logger.error("Some error was detected in FailureDetector StateReporter", ex);
        }
        
    }

    @Override
    public String getName() throws Exception {
        return this.getModuleType().name();
    }
    
}
